package com.zx._12_算法.数据结构.link;


/**
 * @version v1.0
 * @Project: knowledge
 * @Title: Demo5
 *         查找单链表的中间结点（普通模式）
 * @author: zhangxue
 * @date: 2019年7月27日下午8:34:11
 * @company: 未知之地
 * @Copyright: Copyright (c) 2019
 */
public class Demo5 {

    public static void main(String[] args) {
        Node<Integer> node1 = getNodes(1);
        Node<Integer> node2 = getNodes(1, 2);
        Node<Integer> node3 = getNodes(1, 2, 3);
        Node<Integer> node4 = getNodes(1, 2, 3, 4);
        Node<Integer> node5 = getNodes(1, 2, 3, 4, 5);
        Node<Integer> node6 = getNodes(1, 2, 3, 4, 5, 6);

        System.out.println(findMiddle(node1));
        System.out.println(findMiddle(node2));
        System.out.println(findMiddle(node3));
        System.out.println(findMiddle(node4));
        System.out.println(findMiddle(node5));
        System.out.println(findMiddle(node6));
    }

    public static Integer findMiddle(Node<Integer> head) {
        Node<Integer> fast = head;
        Node<Integer> slow = head;

        while (fast != null && slow != null) {
            if ((fast = fast.next) == null) {
                continue;
            } else {
                fast = fast.next;
            }
            slow = slow.next;
        }
        return slow.data;
    }

    public static Node<Integer> getNodes(Integer... nums) {
        Node<Integer> result = new Node<>();
        result.data = nums[0];

        Node<Integer> node = result;
        for (int i = 1; i < nums.length; i++) {
            Node<Integer> node2 = new Node<>();
            node2.data = nums[i];
            node.next = node2;
            node = node2;
        }
        return result;
    }


    static class Node<T> {

        T data;
        Node<T> next;
    }
}
